package tecentyun

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"

	"github.com/apache/incubator-answer/internal/store"
	"github.com/segmentfault/pacman/log"
	"github.com/tencentyun/cos-go-sdk-v5"
)

// COSConfig 腾讯云 COS 配置
type OSS struct {
	Endpoint   string `json:"endpoint" mapstructure:"endpoint" yaml:"endpoint"`
	AccessKey  string `json:"access_key" mapstructure:"access_key" yaml:"access_key"`
	SecretKey  string `json:"secret_key" mapstructure:"secret_key" yaml:"secret_key"`
	BucketName string `json:"bucket_name" mapstructure:"bucket_name" yaml:"bucket_name"`
}

// Global COS Client
var (
	OSSClient   *cos.Client
	OSSBucket   *cos.Bucket
	OSSEndpoint string
)

// InitCOS 初始化 COS 客户端
func InitOSS(cfg OSS) error {
	if cfg.Endpoint == "" || cfg.AccessKey == "" || cfg.SecretKey == "" || cfg.BucketName == "" {
		log.Errorf("腾讯云 COS 配置无效")
		return fmt.Errorf("腾讯云 COS 配置无效")
	}

	u, _ := url.Parse(cfg.Endpoint)
	b := &cos.BaseURL{BucketURL: u}
	OSSClient = cos.NewClient(b, &http.Client{
		Transport: &cos.AuthorizationTransport{
			SecretID:  cfg.AccessKey,
			SecretKey: cfg.SecretKey,
		},
	})
	OSSEndpoint = cfg.Endpoint

	return nil
}

// UploadPutObject 上传文件到 COS
func UploadPutObject(fileName string, src io.Reader) (*store.UploadRes, error) {
	// 检查 COSBucket 是否已初始化
	if OSSClient == nil {
		log.Errorf("COSBucket 未初始化")
		return nil, fmt.Errorf("COSBucket 未初始化")
	}

	// 检查 src 是否为 nil
	if src == nil {
		log.Errorf("src 为 nil")
		return nil, fmt.Errorf("src 为 nil")
	}

	// 去掉文件名中的空格
	fileName = strings.ReplaceAll(fileName, " ", "")

	// 指定文件在 COS 中的路径和名称
	objectKey := "uploads/" + fileName // 例如 "uploads/image.jpg"

	// 尝试上传文件
	_, err := OSSClient.Object.Put(context.Background(), objectKey, src, nil)
	if err != nil {
		log.Errorf("上传文件失败: %v", err)
		return nil, err
	}

	// 构建资源路径
	downloadUrl := fmt.Sprintf(OSSEndpoint + "/" + objectKey)

	fmt.Printf("File uploaded successfully! Resource URL: %s\n", downloadUrl)
	return &store.UploadRes{DownloadURL: downloadUrl}, nil
}
